package com.greet.service.impl;

import com.greet.constant.MessageConstant;
import com.greet.constant.PasswordConstant;
import com.greet.constant.StatusConstant;
import com.greet.context.BaseContext;
import com.greet.dto.EmployeeDTO;
import com.greet.dto.EmployeeLoginDTO;
import com.greet.dto.EmployeePageQueryDTO;
import com.greet.dto.PasswordEditDTO;
import com.greet.entity.Employee;
import com.greet.exception.AccountLockedException;
import com.greet.exception.AccountNotFoundException;
import com.greet.exception.PasswordErrorException;
import com.greet.mapper.EmployeeMapper;
import com.greet.properties.JwtProperties;
import com.greet.result.PageResult;
import com.greet.service.EmployeeService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public boolean addNewEmployee(EmployeeDTO employeeDTO) {
        Employee emp = new Employee();
        //对象属性拷贝
        BeanUtils.copyProperties(employeeDTO, emp);
        emp.setUpdateUser(BaseContext.getCurrentId());
        emp.setCreateUser(BaseContext.getCurrentId());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setCreateTime(LocalDateTime.now());

        //设置账号状态,默认正常状态,1正常，0锁定
        emp.setStatus(StatusConstant.ENABLE);
        //设置密码
        emp.setPassword(DigestUtils
                .md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        //记录创建时间和修改时间

        // 记录当前这条记录的创建人id;
        //每次请求都是一个线程，在拦截器阶段，已经将当前用户id保存了下来


        employeeMapper.insert(emp);
        return true;
    }

    @Override
    public PageResult getPageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //开始分页查询，设置分页
        //调用sql
        employeePageQueryDTO.setPage(
                (employeePageQueryDTO.getPage() - 1) * employeePageQueryDTO.getPageSize()
        );
        List<Employee> employeePage = employeeMapper.selectPageQuery(employeePageQueryDTO);
        Long total = employeeMapper.countAll();
        return new PageResult(total, employeePage);
    }

    @Override
    public void setStatus(Integer status, Long id) {
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
                .build();
        employeeMapper.update(employee);
    }

    @Override
    public void updateEmp(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
    }

    @Override
    public Employee selectById(Long id) {
        Employee employee = employeeMapper.selectById(id);
        employee.setPassword("****");
        return employee;
    }

    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        //通过id查询员工信息
        Employee employee = employeeMapper.selectById(passwordEditDTO.getEmpId());
        //获取旧密码进行比对,密码错误则抛出异常
        String oldPasswd = passwordEditDTO.getOldPassword();
        oldPasswd = DigestUtils.md5DigestAsHex(oldPasswd.getBytes());
        if (!oldPasswd.equals(employee.getPassword())) {
            //旧密码错误
            throw new PasswordErrorException("旧密码错误");
        }
        //将新密码加密后填入数据库
        String newPasswd = passwordEditDTO.getNewPassword();
        newPasswd = DigestUtils.md5DigestAsHex(newPasswd.getBytes());
    }

}
